#include "illegal_parking_tracker.h"

#include <stdio.h>
#include <math.h>
#include <cstdlib>

#include "hw_app_log.h"
#include "hw_app_config.h"
#include "illegal_parking_track.h"


namespace gc
{
    IllegalParkingTracker::IllegalParkingTracker()
    {
    }

    IllegalParkingTracker::~IllegalParkingTracker(void)
    {
    }

    vector<InoutTrack> IllegalParkingTracker::update(const vector<GCTrackObj>& track_objs)
    {
        struct timespec time1 = {0, 0};
        struct timespec time2 = {0, 0};

        LOG_DEBUG("size of track_objs=%d, size of m_inout_tracks=%d", track_objs.size(), m_inout_tracks.size());

        vector<InoutTrack> track_with_inouts;
        vector<int> track_id_added;
        for (auto track_obj: track_objs) {
            bool is_new_track = true;
            int track_id = track_obj.track_id;
            for (auto &inout_track: m_inout_tracks) {
                if (inout_track.m_track_end) {
                    continue;
                }
                if (track_obj.camera_key == inout_track.m_camera_key && track_id == inout_track.m_track_id) {
                    is_new_track = false;
                    bool result = inout_track.AddTrackObj(track_obj);
                    if (result) {
                        track_id_added.emplace_back(track_id);
                    }
                    break;
                }
            }
            if (is_new_track) {
                IllegalParkingTrack inout_track(track_obj.camera_key, track_obj.track_id);
                inout_track.AddTrackObj(track_obj);
                m_inout_tracks.emplace_back(inout_track);

                track_id_added.emplace_back(track_obj.track_id);

                LOG_DEBUG("camera_key=%s, track_id=%d add new track", inout_track.m_camera_key.c_str(), inout_track.m_track_id);
            }
        }
        bool hasNewObj = false;
        for (auto &inout_track: m_inout_tracks) {
            if (inout_track.m_track_end || inout_track.m_dirty) {
                continue;
            }

            hasNewObj = std::find(track_id_added.begin(), track_id_added.end(), inout_track.m_track_id) != track_id_added.end();
            inout_track.update(hasNewObj);

            if (inout_track.m_track_end && inout_track.m_track_result.inout != InoutType::INIT) {
                track_with_inouts.emplace_back(inout_track);
            }
        }
        // 这里状态为m_track_end即可删除，因为InoutTrack实例已经拷贝到track_with_inouts
        m_inout_tracks.erase(std::remove_if(m_inout_tracks.begin(), m_inout_tracks.end(), [](InoutTrack inout_track) { return inout_track.m_track_end || inout_track.m_dirty; }), m_inout_tracks.end());

        LOG_DEBUG("size of m_inout_tracks=%d, size of track_with_inouts=%d", m_inout_tracks.size(), track_with_inouts.size());

        return track_with_inouts;
    }
}